package com.demandbreakdown.xiyun.config;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 腾讯云COS对象存储配置类
 *
 * @author poxz
 */
@Configuration
@ConditionalOnProperty(name = "storage.type", havingValue = "cos")
@ConfigurationProperties(prefix = "cos.client")
@Slf4j
@Data
public class CosConfig {

    /**
     * COS服务域名
     */
    private String host;

    /**
     * 腾讯云密钥ID
     */
    private String secretId;

    /**
     * 腾讯云密钥Key
     */
    private String secretKey;

    /**
     * COS所属地区
     */
    private String region;

    /**
     * COS存储桶名称
     */
    private String bucket;

    /**
     * 应用关闭时，关闭COS客户端
     * 根据官方文档，确保资源正确释放
     */
    private COSClient cosClientInstance;

    /**
     * 创建COS客户端Bean
     * 根据官方文档配置最佳实践
     */
    @Bean
    public COSClient cosClient() {
        // 1. 初始化用户身份信息（secretId, secretKey）- 去除可能的空格
        String trimmedSecretId = secretId.trim();
        String trimmedSecretKey = secretKey.trim();
        COSCredentials cred = new BasicCOSCredentials(trimmedSecretId, trimmedSecretKey);

        log.info("初始化 COS 客户端: bucket={}, region={}, secretId={}***",
                bucket, this.region, trimmedSecretId.substring(0, Math.min(10, trimmedSecretId.length())));

        // 2. 设置bucket的地域，COS地域的简称请参照官方文档
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);

        // 3. 根据官方建议，设置HTTPS协议
        clientConfig.setHttpProtocol(HttpProtocol.https);

        // 4. 设置socket超时时间，默认为30s
        clientConfig.setSocketTimeout(30 * 1000);

        // 5. 设置建立连接的超时时间，默认为30s
        clientConfig.setConnectionTimeout(30 * 1000);

        // 7. 生成COS客户端并保存实例以便销毁
        cosClientInstance = new COSClient(cred, clientConfig);
        log.info("COS 客户端初始化成功");
        return cosClientInstance;
    }

    @PreDestroy
    public void shutdown() {
        if (cosClientInstance != null) {
            cosClientInstance.shutdown();
        }
    }
}
